// src/services/sponsorDashboardService/scholarshipsByCompany.ts

import { BASE_URL } from '@/services/apiConfig';

// Response data item interface - matches backend CompanyScholarshipItem
export interface CompanyScholarshipItem {
  company_name: string;
  program_code: string;
  program_year: number;
  position: number;
  total_amount_per_position: number;
  sponsorship_cost: number;
  status: string;
}

// Pagination metadata interface
export interface PageMeta {
  total: number;
  page: number;
  page_size: number;
}

// Complete response interface
export interface CompanyScholarshipResponse {
  meta: PageMeta;
  items: CompanyScholarshipItem[];
}

// Request parameters interface
export interface CompanyScholarshipParams {
  year_from: number;
  year_to: number;
  current?: boolean;
  program_code?: string;
  page?: number;
  page_size?: number;
}

export const fetchScholarshipsByCompany = async (
  params: CompanyScholarshipParams
): Promise<CompanyScholarshipResponse> => {
  const token = localStorage.getItem('token');
  if (!token) {
    throw new Error('No token found');
  }

  // Build query parameters
  const query = new URLSearchParams();

  // Required parameters
  query.append('year_from', params.year_from.toString());
  query.append('year_to', params.year_to.toString());

  // Optional parameters
  if (params.current !== undefined) {
    query.append('current', params.current.toString());
  }
  if (params.program_code) {
    query.append('program_code', params.program_code);
  }
  if (params.page) {
    query.append('page', params.page.toString());
  }
  if (params.page_size) {
    query.append('page_size', params.page_size.toString());
  }

  try {
    const response = await fetch(`${BASE_URL}/sponsors/research/scholarships-by-company?${query.toString()}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
    }

    const data: CompanyScholarshipResponse = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching scholarships by company:', error);
    throw error;
  }
};
